package com.gingko.duominuo.network

import com.gingko.duominuo.utils.logi
import com.gingko.duominuo.utils.md5
import com.google.gson.Gson
import java.net.URLEncoder
import java.util.*


/**
 * 获取query参数
 *
 * @param path       请求路径
 * @param signParams 需要签名的参数
 * @return query参数
 */
fun assemblyQueryParams(
    path: String,
    signParams: MutableMap<String, Any> = mutableMapOf()
): Map<String, Any> {
    val queryParams = HashMap<String, Any>()
    queryParams["appkey"] =" BuildConfig.APP_KEY"
    queryParams["signt"] = System.currentTimeMillis().toString()
    queryParams["nonce"] = UUID.randomUUID().toString()
    queryParams.putAll(signParams)
    queryParams["sign"] = sign(path, queryParams).toLowerCase(Locale.ROOT)
    return queryParams
}

fun showParams(request: Map<String?, Any?>?) {
    if (request == null || request.isEmpty()) {
        "no requestParams".logi()
    }
    "[http request]:${Gson().toJson(request)}".logi()
}

fun logParams(params: Map<String?, Any?>) {
    val sb = StringBuilder()
    for ((key, value) in params) {
        sb.append(key).append("=").append(value).append("&")
    }
    "[http request]:$sb".logi()
}

/**
 * 生成签名参数
 *
 * @param path      请求地址（不要前面的“/”）
 * @param params    query参数
 * @param secretKey 配置的secretKey
 * @return 签名参数
 */
private fun sign(path: String, params: Map<String, Any>): String {
    val mapSort = params.entries.sortedBy { it.key }.associateBy({ it.key }, { it.value })
    val sb = StringBuilder()
    sb.append(path).append("_")
    for ((key, value) in mapSort) {
        sb.append(key).append("=").append(value.toString()).append("_")
    }
    sb.append("BuildConfig.SECRET_KEY")
    return try {
        val baseString1 = URLEncoder.encode(sb.toString(), "UTF-8")
        baseString1.md5()
    } catch (e: Exception) {
        ""
    }
}
